<template>
  <!-- 登录页面 -->
  <div class="login-page">

    <!-- 头部区域 -->
    <div class="login-header" :style="{ paddingTop: capsuleTop + 'px' }">
      <div class="logo-container">
        <img src="../static/imgs/logo.jpg" alt="Logo" class="logo">
        <div class="app-name">快跑吖</div>
        <div class="app-desc">校园生活服务平台</div>
      </div>
    </div>

    <!-- 登录表单区域 -->
    <div class="login-content">
      <div class="login-card">

        <!-- 微信授权登录 -->
        <div v-if="activeTab === 0" class="wechat-login">
          <div class="wechat-login-content">
            <div class="wechat-title">微信快速登录</div>
            <div class="wechat-desc">使用微信账号快速登录，享受便捷服务</div>



            <!-- 用户协议 -->
            <div class="agreement-section">
              <wd-checkbox v-model="isAgree" @change="handleAgreementChange">
                <span class="agreement-text">
                  我已阅读并同意
                  <span class="agreement-link" @click.stop="viewUserAgreement" style="color: #1677ff;">《用户协议》</span>
                  和
                  <span class="agreement-link" @click.stop="viewPrivacyPolicy" style="color: #1677ff;">《隐私政策》</span>
                </span>
              </wd-checkbox>
            </div>

            <!-- 微信授权按钮 -->
            <div class="login-btn wechat-btn" :disabled="!isAgree || loading" @click="handleWechatLogin">
              <div v-if="loading" class="loading-spinner"></div>
              <span v-else>微信授权登录</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div @click="handleCancelLogin" class="cancel-login">取消登录</div>

    <!-- 底部说明 -->
    <div class="login-footer">
      <div class="footer-text">
        登录后即可享受完整的服务体验
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Return from '@/components/Return.vue'
import { useLoginStore } from '@/stores/login'
import { getWechatUserInfo } from '@/utils/wechat'

const { token } = useLoginStore()
const loginStore = useLoginStore()

// 页面状态
const capsuleTop = ref(0)
const activeTab = ref(0)
const isAgree = ref(false)
const loading = ref(false)
const countdown = ref(0)

// 手机号登录表单
const phoneForm = ref({
  phone: '',
  code: ''
})

// 计算胶囊按钮位置
const calcCapsuleTop = () => {
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleTop.value = menuButtonInfo.bottom + 20
  // #endif
}

// 切换登录方式
const switchTab = (index) => {
  activeTab.value = index
  // 重置表单
  phoneForm.value = { phone: '', code: '' }
}

// 同意协议状态变化
const handleAgreementChange = (value) => {
  console.log(value.value);

  isAgree.value = value.value
}

// 取消登录
const handleCancelLogin = () => {
  uni.reLaunch({
    url: '/pages/index'
  })
}
// 微信授权登录
const handleWechatLogin = async () => {
  console.log(isAgree.value);

  if (!isAgree.value) {
    uni.showToast({
      title: '请先同意用户协议和隐私政策',
      icon: 'none'
    })
    return
  }

  loading.value = true

  try {
    // 调用登录接口
    const result = await loginStore.aWechatLoginWithUserInfo(true)
    if (result.success) {
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })

      // 跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/index'
        })
      }, 1500)
    } else {
      console.error('微信登录失败:', result.error)
    }

  } catch (error) {
    console.error('微信登录失败:', error)
    uni.showToast({
      title: error.message || '登录失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!phoneForm.value.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }

  if (!/^1[3-9]\d{9}$/.test(phoneForm.value.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }

  try {
    // 调用发送验证码接口
    const res = await Fetch('shopping/sms/send', {
      method: 'POST',
      data: { phone: phoneForm.value.phone }
    })

    if (res.data.code === 200) {
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      })

      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    } else {
      uni.showToast({
        title: res.data.msg || '发送失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '发送失败，请重试',
      icon: 'none'
    })
  }
}

// 手机号登录
const handlePhoneLogin = async () => {
  if (!isAgree.value) {
    uni.showToast({
      title: '请先同意用户协议和隐私政策',
      icon: 'none'
    })
    return
  }

  if (!phoneForm.value.phone || !phoneForm.value.code) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    })
    return
  }

  loading.value = true

  try {
    // 调用手机号登录接口
    const res = await Fetch('shopping/login/phone', {
      method: 'POST',
      data: {
        phone: phoneForm.value.phone,
        code: phoneForm.value.code
      }
    })

    if (res.data.code === 200) {
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })

      // 跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: '/pages/index'
        })
      }, 1500)
    } else {
      uni.showToast({
        title: res.data.msg || '登录失败',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}


// 查看用户协议
const viewUserAgreement = () => {
  uni.navigateTo({
    url: '/pages-shift/UserAgreement'
  })
}

// 查看隐私政策
const viewPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages-shift/PrivacyPolicy'
  })
}

onMounted(() => {
  calcCapsuleTop()
})

const gotoHome  = ref(true)
onLoad((options) => {
  if (options.type === 'logout') {
    uni.clearStorageSync()
    gotoHome.value = false
  }

  // getMyShopInfo()


})
// 使用原生 uni.request 请求
const getMyShopInfo = async () => {

  try {
    const result = await new Promise((resolve, reject) => {
      uni.request({
        url: `${baseUrl}shopping/shopInfo/getMyInfo`,
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'accesstoken': token,
        },
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
    if (result.data.code === 200 && gotoHome.value) {
      uni.reLaunch({
        url: '/pages/index'
      })
    }


  } catch (error) {

    return null
  }
}


</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #F9DC40 0%, #FFFFFF 30%);
  display: flex;
  flex-direction: column;

  .login-header {
    padding: 0 40rpx;
    margin-bottom: 60rpx;

    .logo-container {
      text-align: center;
      padding: 60rpx 0;

      .logo {
        width: 120rpx;
        height: 120rpx;
        border-radius: 24rpx;
        margin-bottom: 20rpx;
      }

      .app-name {
        font-size: 48rpx;
        font-weight: bold;
        color: #191919;
        margin-bottom: 16rpx;
      }

      .app-desc {
        font-size: 28rpx;
        color: #666666;
      }
    }
  }

  .login-content {
    flex: 1;
    padding: 0 40rpx;
    margin-bottom: 60rpx;

    .login-card {
      background: #FFFFFF;
      border-radius: 24rpx;
      padding: 40rpx;
      box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);

      .login-tabs {
        display: flex;
        margin-bottom: 40rpx;
        background: #F5F5F5;
        border-radius: 16rpx;
        padding: 8rpx;

        .tab-item {
          flex: 1;
          height: 72rpx;
          line-height: 72rpx;
          text-align: center;
          font-size: 28rpx;
          color: #666666;
          border-radius: 12rpx;
          transition: all 0.3s;

          &.active {
            background: #F9DC40;
            color: #191919;
            font-weight: bold;
          }
        }
      }

      .wechat-login {
        .wechat-login-content {
          text-align: center;

          .wechat-icon {
            width: 120rpx;
            height: 120rpx;
            margin: 0 auto 24rpx;
            background: #F9DC40;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
              width: 60rpx;
              height: 60rpx;
            }
          }

          .wechat-title {
            font-size: 32rpx;
            font-weight: bold;
            color: #191919;
            margin-bottom: 16rpx;
          }

          .wechat-desc {
            font-size: 26rpx;
            color: #666666;
            margin-bottom: 40rpx;
            line-height: 1.5;
          }

          .auth-info {
            margin-bottom: 40rpx;

            .auth-item {
              display: flex;
              align-items: center;
              justify-content: center;
              margin-bottom: 16rpx;

              .auth-dot {
                width: 8rpx;
                height: 8rpx;
                background: #F9DC40;
                border-radius: 50%;
                margin-right: 16rpx;
              }

              span {
                font-size: 24rpx;
                color: #666666;
              }
            }
          }
        }
      }

      .phone-login {
        .input-group {
          margin-bottom: 40rpx;

          .input-item {
            margin-bottom: 24rpx;

            .phone-input,
            .code-input {
              width: 100%;
              height: 88rpx;
              background: #F8F8F8;
              border-radius: 16rpx;
              padding: 0 24rpx;
              font-size: 28rpx;
              border: none;
              box-sizing: border-box;
            }

            &.verification-group {
              display: flex;
              gap: 20rpx;

              .code-input {
                flex: 1;
              }

              .send-code-btn {
                width: 200rpx;
                height: 88rpx;
                background: #F9DC40;
                color: #191919;
                border: none;
                border-radius: 16rpx;
                font-size: 26rpx;
                font-weight: bold;

                &:disabled {
                  background: #E0E0E0;
                  color: #999999;
                }
              }
            }
          }
        }
      }

      .agreement-section {
        margin-bottom: 40rpx;

        .agreement-checkbox {
          .agreement-text {
            font-size: 26rpx;
            color: #666666;
            line-height: 1.5;

            .agreement-link {
              color: #F9DC40;
              text-decoration: underline;
            }
          }
        }
      }

      .login-btn {
        width: 100%;
        height: 88rpx;
        border-radius: 44rpx;
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        position: relative;

        &.wechat-btn {
          background: #F9DC40;
          color: #191919;

          &:disabled {
            background: #E0E0E0;
            color: #999999;
          }
        }

        &.phone-btn {
          background: #F9DC40;
          color: #191919;

          &:disabled {
            background: #E0E0E0;
            color: #999999;
          }
        }

        .loading-spinner {
          width: 32rpx;
          height: 32rpx;
          border: 3rpx solid #FFFFFF;
          border-top: 3rpx solid transparent;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }
      }

      .other-login {
        .divider {
          display: flex;
          align-items: center;
          margin-bottom: 32rpx;

          .divider-line {
            flex: 1;
            height: 1rpx;
            background: #E0E0E0;
          }

          .divider-text {
            padding: 0 24rpx;
            font-size: 24rpx;
            color: #999999;
          }
        }

        .other-login-options {
          display: flex;
          justify-content: center;

          .login-option {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20rpx;

            img {
              width: 48rpx;
              height: 48rpx;
              margin-bottom: 12rpx;
            }

            span {
              font-size: 24rpx;
              color: #666666;
            }
          }
        }
      }
    }
  }

  .login-footer {
    padding: 0 40rpx 40rpx;
    text-align: center;

    .footer-text {
      font-size: 24rpx;
      color: #999999;
    }
  }
  .cancel-login {
    font-size: 24rpx;
    color: #999999;
    text-align: center;
    margin-bottom: 40rpx;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}
</style>
